package com.github.cdisk.xtrans.ui;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.ExpandBar;
import org.eclipse.swt.widgets.ExpandItem;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.wb.swt.SWTResourceManager;

import com.github.cdisk.xtrans.ui.properties.PropertiesFile;
import com.github.cdisk.xtrans.ui.toolbox.AttributeBoxLoader;
import com.github.cdisk.xtrans.ui.toolbox.ComponentBoxLoader;
import com.github.cdisk.xtrans.ui.toolbox.ConnectTable;
import com.github.cdisk.xtrans.ui.toolbox.ObjectListBox;
import com.github.cdisk.xtrans.ui.widget.TimeIntervalDialog;


public class MainWindow {

	private Shell shell;
	private CanvasPanel canvas;
	private ExpandBar expandBar;
	private Tree tree;
	
	private Context context = new Context();
	private ConnectTable connectTable;
	private ObjectListBox listObjects;

	/**
	 * Launch the application.
	 * @param args
	 */
	public static void main(String[] args) {
		MainWindow window = new MainWindow();
		window.open();
	}

	/**
	 * Open the window.
	 */
	public void open() {
		Display display = Display.getDefault();
		createContents();
		config(); // 初始化Context

		/* 默认打开最后一次打开文件 */
		try {
			String lastOpenFile = PropertiesFile.get("lastOpenFile");
			if (StringUtils.isNotEmpty(lastOpenFile)) {
				Operation.loadFile(lastOpenFile, shell, canvas);
				reflush();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		/* 设置快捷键 */
		display.addFilter(SWT.KeyDown, new Listener() {
			@Override
			public void handleEvent(Event e) {
				if (e.stateMask == SWT.CTRL) {
					if (e.keyCode == 115) { // S 保存
						Operation.save(shell);
					} else if (e.keyCode == 111) { // O 打开
						Operation.open(shell, canvas);
						reflush();
					} else if (e.keyCode == 110) { // N 新建
						newFile();
					}
				}
				if (e.stateMask == (SWT.SHIFT | SWT.CTRL)) {
					if (e.keyCode == 115) { // S 另存为
						Operation.saveAs(shell);
					}
				}
			}
		});
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}
	
	protected void reflush() {
		connectTable.reflush(); // 初始化右侧连接
		listObjects.reflushItems(); // 刷新对象列表
	}

	/**
	 * Create contents of the window.
	 */
	protected void createContents() {
		shell = new Shell();
		shell.setSize(819, 662);
		shell.setText("转换编辑器 - 新的转换");
		shell.setLayout(new FillLayout(SWT.HORIZONTAL));
		shell.setMaximized(true);

		Menu menu = new Menu(shell, SWT.BAR);
		shell.setMenuBar(menu);

		MenuItem mntmn = new MenuItem(menu, SWT.NONE);
		mntmn.setText("新建(&N)");
		mntmn.setImage(SWTResourceManager.getImage(ComponentBoxLoader.class.getResource("/").getPath() + "/icon/page_white_add.png"));
		mntmn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				newFile();
			}
		});

		MenuItem mntms = new MenuItem(menu, SWT.NONE);
		mntms.setText("打开(&O)");
		mntms.setImage(SWTResourceManager.getImage(ComponentBoxLoader.class.getResource("/").getPath() + "/icon/folder_page.png"));
		mntms.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				Operation.open(shell, canvas);
				reflush();
			}
		});

		MenuItem mntmNewItem = new MenuItem(menu, SWT.NONE);
		mntmNewItem.setText("保存(&S)");
		mntmNewItem.setImage(SWTResourceManager.getImage(ComponentBoxLoader.class.getResource("/").getPath() + "/icon/disk.png"));
		mntmNewItem.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				Operation.save(shell);
			}
		});

		MenuItem mntmNewItem_1 = new MenuItem(menu, SWT.NONE);
		mntmNewItem_1.setText("另存为");
		mntmNewItem_1.setImage(SWTResourceManager.getImage(ComponentBoxLoader.class.getResource("/").getPath() + "/icon/disk_multiple.png"));
		mntmNewItem_1.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				Operation.saveAs(shell);
			}
		});
		
		MenuItem menuItem_1 = new MenuItem(menu, SWT.SEPARATOR);
		menuItem_1.setText("-");
		
		MenuItem mntmr = new MenuItem(menu, SWT.NONE);
		mntmr.setText("运行(&R)");
		mntmr.setImage(SWTResourceManager.getImage(ComponentBoxLoader.class.getResource("/").getPath() + "/icon/play_green.png"));
		mntmr.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				Operation.save(shell);
				String file = Operation.CONFIG.file;
				try {
					/* 调用xtrans-core启动文件，并努力使cmd窗口执行后不关闭。 */
					String cmd = "cmd /c start cmd /k java -classpath .;./*;./xtrans-core_lib/*;driver_lib/* Main \"" + file + "\"";
					Runtime.getRuntime().exec(cmd);
				} catch (IOException e1) {
					e1.printStackTrace();
					MessageBox msg = new MessageBox(shell, SWT.NONE);
					msg.setText("错误！");
					msg.setMessage(e1.getMessage());
					msg.open();
				}
			}
		});

		MenuItem mntmTime = new MenuItem(menu, SWT.NONE);
		mntmTime.setText("定时(&T)");
		mntmTime.setImage(SWTResourceManager.getImage(ComponentBoxLoader.class.getResource("/").getPath() + "/icon/time.png"));
		mntmTime.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				TimeIntervalDialog dialog = new TimeIntervalDialog(shell, Operation.CONFIG);
				dialog.open();
			}
		});

		SashForm sashForm = new SashForm(shell, SWT.NONE);

		TabFolder tabFolder_1 = new TabFolder(sashForm, SWT.NONE);
		TabItem tabItem_2 = new TabItem(tabFolder_1, SWT.NONE);
		tabItem_2.setText("组件");

		expandBar = new ExpandBar(tabFolder_1, SWT.NONE);
		expandBar.addControlListener(new ControlAdapter() {
			@Override
			public void controlResized(ControlEvent e) {
				ExpandItem[] expandItems = expandBar.getItems();
				for (ExpandItem item : expandItems) {
					Composite composite = (Composite) item.getControl();
					Point point = composite.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
					item.setHeight(point.y);
				}
			}
		});
		tabItem_2.setControl(expandBar);

		TabItem tabItem_4 = new TabItem(tabFolder_1, SWT.NONE);
		tabItem_4.setText("对象");

		listObjects = new ObjectListBox(tabFolder_1, SWT.BORDER);
		tabItem_4.setControl(listObjects);

		ScrolledComposite scrolledComposite = new ScrolledComposite(sashForm, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
		scrolledComposite.setExpandHorizontal(true);
		scrolledComposite.setExpandVertical(true);

		Composite composite = new Composite(scrolledComposite, SWT.NONE);
		canvas = new CanvasPanel(composite, SWT.DOUBLE_BUFFERED, context);
		canvas.setBounds(0, 0, 100, 100);
		scrolledComposite.setContent(composite);
		scrolledComposite.setMinSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));

		

		TabFolder tabFolder = new TabFolder(sashForm, SWT.NONE);
		
		TabItem tabItem_3 = new TabItem(tabFolder, SWT.NONE);
		tabItem_3.setText("属性");

		tree = new Tree(tabFolder, SWT.BORDER); // 属性面板
		tree.setLinesVisible(true);
		tree.setHeaderVisible(true);
		tabItem_3.setControl(tree);

		TreeColumn trclmnNewColumnName = new TreeColumn(tree, SWT.NONE);
		trclmnNewColumnName.setWidth(100);
		trclmnNewColumnName.setText("属性");

		TreeColumn trclmnNewColumnValue = new TreeColumn(tree, SWT.NONE);
		trclmnNewColumnValue.setWidth(150);
		trclmnNewColumnValue.setText("值");

		TreeColumn trclmnNewColumn = new TreeColumn(tree, SWT.NONE);
		trclmnNewColumn.setWidth(100);
		trclmnNewColumn.setText("说明");

		TabItem tabItem = new TabItem(tabFolder, SWT.NONE);
		tabItem.setText("连接");

		connectTable = new ConnectTable(tabFolder, SWT.BORDER | SWT.FULL_SELECTION);
		tabItem.setControl(connectTable);

		sashForm.setWeights(new int[] {100, 300, 100});

	}

	/**
	 * 初始化context和控制类的初始化
	 */
	private void config() {
		context.setAttribute(tree); // 属性面板
		context.setCanvas(canvas); // 画布面板
		context.setConnect(connectTable);  // 连接面板
		context.setListObjects(listObjects); // 对象面板
		context.setToolbox(expandBar);  // 元件面板
		canvas.setOnAttributeLoad(new AttributeBoxLoader(context));
		ComponentBoxLoader.initComponents(context); // 初始化左侧工具栏
	}

	/**
	 * 新建事件
	 */
	private void newFile() {
		if (Operation.CONFIG.components.size() > 0 || Operation.CONFIG.connects.size() > 0) {
			MessageBox mb = new MessageBox(shell, SWT.ICON_WARNING | SWT.YES | SWT.NO);
			mb.setText("Tips");
			mb.setMessage("当前有文件正在编辑，是否要继续新建？");
			if (mb.open() != SWT.YES) {
				return;
			}
		}
		Operation.loadFile(null, shell, canvas);
		reflush();
	}
}
